package com.lemote.action.order;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lemote.action.BaseAction;
import com.lemote.core.Page;
import com.lemote.core.PropertyFilter;
import com.lemote.entity.CircuitBoard;
import com.lemote.entity.FlowTask;
import com.lemote.entity.OrderEntity;
import com.lemote.entity.ShowEntity;
import com.lemote.entity.User;
import com.lemote.exception.AppException;
import com.lemote.service.order.CircuitBoardService;
import com.lemote.service.order.FlowTaskService;
import com.lemote.service.order.OrderService;
import com.lemote.service.order.ShowEntityService;
import com.lemote.utils.Constant;

/**
 * 
 * @author wuhui
 * @time 2011-7-20 下午08:46:28
 * @Version:0.0.1
 * @since smt
 */
@Service("circuitBoardAction")
public class CircuitBoardAction extends
		BaseAction<CircuitBoard, CircuitBoardService> {

	private CircuitBoard circuitBoard;

	private FlowTaskService flowTaskService;

	private ShowEntityService showEntityService;

	private OrderService orderService;

	private String msg;

	private List<OrderEntity> orders;

	private String message;

	ByteArrayInputStream inputStream;
	
	private String orderNo;
	
	//Mac地址输入节点工作状态0：当前任务状态，1:当前生产状
	private String proStauts;

	@Override
	public String delete() throws AppException {

		return null;
	}

	/**
	 * 添加mac地址
	 * 
	 * @return
	 */
	public String macSave() {
		String cboardid = request.getParameter("cboardid");
		FlowTask macTask = flowTaskService.getTaskByTaskName("ft_test");
		if (cboardid != null && !"".equals(StringUtils.trim(cboardid))) {
			String mac = request.getParameter("mac");
			if (mac != null && !"".equals(StringUtils.trim(mac))) {
				User macUser = (User) request.getSession().getAttribute(
						Constant.SESSION_USER);
				CircuitBoard board = entityService.get("icNo", cboardid);
				if (board == null) {
					message = "*没有找到编号为 " + cboardid + " 的主板";
					return SUCCESS;
				}
				message = "";
				board.setMacDate(new Date());
				board.setMacNo(mac);
				board.setPreTask(board.getFlowTask());
				board.setFlowTask(macTask);
				board.setMacUser(macUser);
				entityService.update(board);
				ShowEntity show = showEntityService.get("orderNo", board
						.getOrderNo());
				show.setDipCompleteNum(show.getDipCompleteNum() + 1);
				show.setDipYield(show.getDipYield() + 1);
				showEntityService.update(show);
				this.msg = "Y";
				return SUCCESS;
			}
		}
		return ERROR;
	}

	/**
	 * 添加mac地址
	 * 
	 * @return
	 */
	public String allMacSave() {
		FlowTask macTask = flowTaskService.getTaskByTaskName("ft_test");
		String mac = request.getParameter("mac");
		if (mac != null && !"".equals(StringUtils.trim(mac))) {
			User macUser = (User) request.getSession().getAttribute(
					Constant.SESSION_USER);
			String[] macs = mac.split("=");
			if (macs != null && macs.length > 0) {
				for (String m : macs) {
					if (m != null && !"".equals(m)) {
						String[] ids = m.split("-");
						if (ids != null && ids.length > 0) {
							CircuitBoard board = entityService.get(Long
									.parseLong(ids[0]));
							board.setMacDate(new Date());
							board.setMacNo(ids[1]);
							board.setPreTask(board.getFlowTask());
							board.setFlowTask(macTask);
							board.setMacUser(macUser);
							entityService.update(board);
							ShowEntity show = showEntityService.get("orderNo",
									board.getOrderNo());
							show
									.setDipCompleteNum(show.getDipCompleteNum() + 1);
							show.setDipYield(show.getDipYield() + 1);
							showEntityService.update(show);
						}
					}
				}
				this.msg = "Y";
				return SUCCESS;
			}
		}
		return ERROR;
	}

	@Override
	public String input() throws AppException {

		prepareModel();
		if (circuitBoard.getId() != null) {
			return SUCCESS;
		}
		return SUCCESS;
	}

	/**
	 * 自动检测BOT AOI站点所有板子
	 * 
	 * @return
	 */
	public String botAutoTest() {
		User user = (User) request.getSession().getAttribute(
				Constant.SESSION_USER);
		if (user != null) {
			List<CircuitBoard> boards = entityService.getAllBoard(user
					.getRoleIds());
			try {
				entityService.autoBotTest(boards, user);
			} catch (Exception e) {
				e.printStackTrace();
				msg = "N";
			}
			msg = "Y";
		}

		return SUCCESS;
	}

	/**
	 * 测试指定板子
	 * 
	 * @return
	 */
	public String botTest() {
		String bid = request.getParameter("bid");
		User user = (User) request.getSession().getAttribute(
				Constant.SESSION_USER);
		if (user != null) {
			List<CircuitBoard> boards = new ArrayList<CircuitBoard>();
			CircuitBoard board = entityService.get(Long.parseLong(bid));
			boards.add(board);
			try {
				entityService.autoBotTest(boards, user);
			} catch (Exception e) {
				e.printStackTrace();
				msg = "N";
			}
			msg = "Y";
		}
		return SUCCESS;
	}

	/**
	 * bot 站点不良
	 * 
	 * @return
	 */
	public String botNg() {
		String bid = request.getParameter("bid");
		try {
			if (bid != null && !"".equals(StringUtils.trim(bid))) {
				Long cid = Long.parseLong(bid);
				CircuitBoard board = entityService.get(cid);
				FlowTask repair = flowTaskService.getTaskByTaskName("repair");
				board.setPreTask(board.getFlowTask());
				board.setStatus("1");
				board.setAnalyzes(1);
				board.setRepair(1);
				if (board != null && board.getRtimes() <= 0) {
					ShowEntity show = showEntityService.get("orderNo", board
							.getOrderNo());
					show.setSmtRepairNum(show.getSmtRepairNum() + 1);
					showEntityService.update(show);
				}
				dealBoard(board);
				board.setFlowTask(repair);
				OrderEntity oe = board.getOrderEntity();
				if (board.getRtimes() != null && board.getRtimes() == 0) {
					oe.setBadNum(oe.getBadNum() + 1);
					oe.setThrough(oe.getThrough() - 1);
				}
				board.setOrderEntity(oe);
				entityService.update(board);
				msg = "Y";
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = "N";
		}
		return SUCCESS;
	}

	/**
	 * top 站点不良
	 * 
	 * @return
	 */
	public String topNg() {
		String boardid = request.getParameter("bid");
		try {
			if (boardid != null && !"".equals(StringUtils.trim(boardid))) {
				Long cbid = Long.parseLong(boardid);
				CircuitBoard board = entityService.get(cbid);
				FlowTask repair = flowTaskService.getTaskByTaskName("repair");
				board.setPreTask(board.getFlowTask());
				board.setStatus("1");
				board.setAnalyzes(1);
				board.setFlowTask(repair);
				if (board != null && board.getRtimes() <= 0) {
					ShowEntity show = showEntityService.get("orderNo", board
							.getOrderNo());
					show.setSmtRepairNum(show.getSmtRepairNum() + 1);
					showEntityService.update(show);
				}
				dealBoard(board);
				entityService.update(board);
				msg = "Y";
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = "N";
		}
		return SUCCESS;
	}

	/**
	 * 
	 * 板子出现不良时更新订单及板子信息
	 * 
	 * @param board
	 */
	private void dealBoard(CircuitBoard board) {
		OrderEntity oe = board.getOrderEntity();
		if (board.getRtimes() != null && board.getRtimes() == 0) {
			oe.setThrough(oe.getThrough() - 1);
		}
		oe.setBadNum(oe.getBadNum() + 1);
		board.setOrderEntity(oe);
		board.setRtimes(board.getRtimes() + 1);
	}

	/**
	 * 自动检测TOP AOI站点所有板子
	 * 
	 * @return
	 */
	public String topAutoTest() {
		User user = (User) request.getSession().getAttribute(
				Constant.SESSION_USER);
		if (user != null) {
			List<CircuitBoard> boards = entityService.getAllBoard(user
					.getRoleIds());
			try {
				entityService.autoTopTest(boards, user);
			} catch (Exception e) {
				e.printStackTrace();
				msg = "N";
			}
			msg = "Y";
		}

		return SUCCESS;
	}

	/**
	 * top 测试站点
	 * 
	 * @return
	 */
	public String topTest() {
		User user = (User) request.getSession().getAttribute(
				Constant.SESSION_USER);
		long bid = Long.valueOf(request.getParameter("bid"));
		if (user != null) {
			CircuitBoard board = entityService.get(bid);
			List<CircuitBoard> boards = new ArrayList<CircuitBoard>();
			boards.add(board);
			try {
				entityService.autoTopTest(boards, user);
			} catch (Exception e) {
				e.printStackTrace();
				msg = "N";
			}
			msg = "Y";
		}

		return SUCCESS;
	}

	/**
	 * 订单列表
	 */
	@Override
	public String list() throws AppException {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(request);
		page.setOrder(Page.DESC);
		page.setOrderBy("id");
		this.orders = orderService.getAll();
		page = entityService.search(page, filters);
		return SUCCESS;
	}

	/**
	 * bot 测试站点
	 * 
	 * @return
	 * @throws AppException
	 */
	public String botList() throws AppException {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(request);
		orderList();
		page.setOrder(Page.DESC);
		page.setOrderBy("id");
		FlowTask flowTask = flowTaskService.getTaskByTaskName("bot_aoi_test");
		page = entityService.searchBoard(page, filters, flowTask);
		return SUCCESS;
	}

	/**
	 * ft站点
	 * 
	 * @return
	 */
	public String ftList() {

		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(request);
		page.setOrder(Page.DESC);
		orderList();
		page.setOrderBy("id");
		FlowTask flowTask = flowTaskService.getTaskByTaskName("ft_test");
		page = entityService.searchBoard(page, filters, flowTask);
		return SUCCESS;
	}

	/**
	 * 
	 * MAC地址列表
	 * 
	 * @return
	 */
	public String macList() {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(request);
		orderList();
		page.setOrder(Page.DESC);
		FlowTask  flowTask = flowTaskService.getTaskByTaskName("ft_test");
		if(proStauts!=null&&"1".equals(proStauts)){
			flowTask = flowTaskService.getTaskByTaskName("mac_input");
			page.setOrderBy("id");
		}else{
			page.setOrderBy("macDate");
		}
		page = entityService.searchBoard(page, filters, flowTask);
		return SUCCESS;
	}

	/**
	 * FT测试
	 * 
	 * @return
	 */
	public String ftTest() {

		String bid = request.getParameter("bid");
		if (bid != null && !"".equals(StringUtils.trim(bid))) {
			Long cid = Long.parseLong(bid);
			FlowTask packageTask = flowTaskService.getTaskByTaskName("package");
			CircuitBoard board = entityService.get(cid);
			if (board == null) {
				this.msg = "N";
				return ERROR;
			}
			ShowEntity show = showEntityService.get("orderNo", board
					.getOrderNo());
			show.setFtCompleteNum(show.getFtCompleteNum() + 1);
			if (!"repair".equals(board.getPreTask().getTaskEname())) {
				show.setFtYield(show.getFtYield() + 1);
			}
			showEntityService.update(show);
			board.setPreTask(board.getFlowTask());
			board.setStatus("0");
			OrderEntity order = board.getOrderEntity();
			order.setPack(true);
			board.setOrderEntity(order);
			board.setFlowTask(packageTask);
			entityService.update(board);
			showEntityService.update(show);
			this.msg = "Y";
		}
		return SUCCESS;
	}

	/**
	 * FT 测试不良
	 * 
	 * @return
	 * @throws AppException
	 */
	public String ftNg() throws AppException {
		prepareModel();
		return SUCCESS;
	}

	/**
	 * TOP AOI 站点
	 * 
	 */
	public String topList() throws AppException {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(request);
		orderList();
		page.setOrder(Page.DESC);
		page.setOrderBy("id");
		PropertyFilter filter = new PropertyFilter("EQS_status", "0");
		filters.add(filter);
		FlowTask flowTask = flowTaskService.getTaskByTaskName("top_aoi_test");
		page = entityService.searchBoard(page, filters, flowTask);
		return SUCCESS;
	}

	public String repairList() {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(request);
		page.setOrder(Page.DESC);
		orderList();
		page.setOrderBy("id");
		PropertyFilter filter = new PropertyFilter("EQI_analyzes", "1");
		filters.add(filter);
		FlowTask flowTask = flowTaskService.getTaskByTaskName("repair");
		page = entityService.searchBoard(page, filters, flowTask);
		return SUCCESS;
	}

	public String analyzelist() {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(request);
		orderList();
		page.setOrder(Page.DESC);
		page.setOrderBy("id");
		PropertyFilter filter = new PropertyFilter("EQI_analyzes", "0");
		filters.add(filter);
		FlowTask flowTask = flowTaskService.getTaskByTaskName("repair");
		page = entityService.searchBoard(page, filters, flowTask);
		return SUCCESS;
	}

	/**
	 * 根据
	 * 
	 * @return
	 */
	@JSON(serialize=false,deserialize=false)
	public String getReport() {
		return SUCCESS;
	}

	@Override
	public void prepareModel() throws AppException {
		if (id != null) {
			circuitBoard = entityService.get(id);
		} else {
			circuitBoard = new CircuitBoard();
		}
	}

	@Override
	public String save() throws AppException {
		setBackUrl("board/list.htm");
		entityService.update(circuitBoard);
		return GLOBALSUCCESS;
	}
	
	public String mac(){
		String mac = request.getParameter("mac");
		CircuitBoard cb = entityService.get("macNo", mac);
		if (cb!=null) {
			this.msg = "Y";
		}else {
			this.msg="N";
		}
		return SUCCESS;
	}

	public void orderList() {
		List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
		PropertyFilter filter = new PropertyFilter("EQS_status", "1");
		filters.add(filter);
		this.orders = orderService.getList(filters);
	}

	public String export() {
		String icNo = request.getParameter("icNo");
		String orderNo = request.getParameter("orderNo");
		String status = request.getParameter("status");

		List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
		if (icNo != null && !"".equals(StringUtils.trim(icNo))) {
			PropertyFilter filter = new PropertyFilter("LIKES_icNo", icNo);
			filters.add(filter);
		}
		if (orderNo != null && !"".equals(StringUtils.trim(orderNo))) {
			PropertyFilter filter = new PropertyFilter("EQS_orderNo", orderNo);
			filters.add(filter);
		}
		if (status != null && !"".equals(StringUtils.trim(status))) {
			PropertyFilter filter = new PropertyFilter("EQS_status", status);
			filters.add(filter);
		}

		List<CircuitBoard> cbs = entityService.getList(filters);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		try {
			WritableWorkbook wwb = Workbook.createWorkbook(baos);
			WritableSheet ws = wwb.createSheet("主板导出信息", 0);
			ws.mergeCells(0, 0, 10, 0);
			Label label = new Label(0, 0, "主板查询导出信息");
			formatLabel(label);
			ws.addCell(label);
			//生成表头
			CreateTitle(ws);
			if (cbs!=null) {
				for (int i = 0; i < cbs.size(); i++) {
					CircuitBoard cb = cbs.get(i);
					createLabel(ws,0, i+2,cb.getIcNo());
					createLabel(ws,1, i+2,cb.getOrderNo());
					createLabel(ws,2, i+2,cb.getMacNo());
					createLabel(ws,3, i+2,com.lemote.utils.StringUtils.dateToString(cb.getMacDate()));
					
					createLabel(ws,4, i+2,cb.getPmonVersion());
					createLabel(ws,5, i+2,cb.getProgramVersion());
					createLabel(ws,6, i+2,cb.getSystemName());
					if ("0".equals(cb.getStatus())) {
						createLabel(ws,7, i+2,"良品");
					}else if ("1".equals(cb.getStatus())) {
						createLabel(ws,7, i+2,"不良品");
					}else if ("2".equals(cb.getStatus())) {
						createLabel(ws,7, i+2,"报废品");
					}
					createLabel(ws,8, i+2,cb.getFlowTask().getTaskName());
					if (cb.getBox()!=null) {
						createLabel(ws,9, i+2,cb.getBox().getBoxNo());
					}else {
						createLabel(ws,9, i+2,"无");
						
					}
					createLabel(ws,10, i+2,cb.getRemark());
				}
			}
			wwb.write();
			wwb.close();
		} catch (IOException e) {
			e.printStackTrace();

		} catch (RowsExceededException e) {
			e.printStackTrace();

		} catch (WriteException e) {
			e.printStackTrace();

		}

		inputStream = new ByteArrayInputStream(baos.toByteArray());
		return SUCCESS;
	}
	
	/**
	 * 生成表头
	  * @param ws
	  * @throws WriteException
	  * @throws RowsExceededException
	 */
	private void CreateTitle(WritableSheet ws) throws WriteException,
			RowsExceededException {
		createLabel(ws,0,1, "板子编号");
		createLabel(ws,1,1, "订单编号");
		createLabel(ws,2,1, "MAC地址");
		createLabel(ws,3,1, "MAC录入时间");
		createLabel(ws,4,1, "PMON版本");
		createLabel(ws,5,1, "程序版本");
		createLabel(ws,6,1, "系统名称");
		createLabel(ws,7,1, "状态");
		createLabel(ws,8,1, "当前站点");
		createLabel(ws,9,1, "包装箱号");
		createLabel(ws,10,1, "备注");
	}
	
	private void createLabel(WritableSheet ws,int c,int r,String content) throws RowsExceededException, WriteException{
		Label label = new Label(c,r, content);
		formatLabel(label);
		ws.addCell(label);
	}

	private void formatLabel(Label label){
		WritableCellFormat cellFormat=new WritableCellFormat();
		try {
			cellFormat.setAlignment(Alignment.CENTRE);
		} catch (WriteException e) {
			e.printStackTrace();
				
		}
		label.setCellFormat(cellFormat);
	}

	public ByteArrayInputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(ByteArrayInputStream inputStream) {
		this.inputStream = inputStream;
	}

	@Autowired
	@Override
	public void setEntityService(CircuitBoardService circuitBoardService) {

		entityService = circuitBoardService;
	}

	@Autowired
	public void setFlowTaskService(FlowTaskService flowTaskService) {
		this.flowTaskService = flowTaskService;
	}

	@Override
	@JSON(serialize=false,deserialize=false)
	public CircuitBoard getModel() {

		return circuitBoard;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	@JSON(serialize=false,deserialize=false)
	public CircuitBoard getCircuitBoard() {
		return circuitBoard;
	}

	public void setCircuitBoard(CircuitBoard circuitBoard) {
		this.circuitBoard = circuitBoard;
	}

	@Autowired
	public void setShowEntityService(ShowEntityService showEntityService) {
		this.showEntityService = showEntityService;
	}
	@JSON(serialize=false,deserialize=false)
	public List<OrderEntity> getOrders() {
		return orders;
	}

	public void setOrders(List<OrderEntity> orders) {
		this.orders = orders;
	}

	@Autowired
	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public String getMessage() {
		return message;
	}

	public String getProStauts() {
		return proStauts;
	}

	public void setProStauts(String proStauts) {
		this.proStauts = proStauts;
	}

	public String getOrderNo() {
		return orderNo;
	}

	public void setOrderNo(String orderNo) {
		this.orderNo = orderNo;
	}

	
	
}
